
package com.scalar.chiptrack.users.actions;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.NotificationSetup;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.NotificationSetupDAO;


public final class NotificationsSetupAction extends ChipTrackAction {


    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws Exception {

        String retval = "failure";

        HashMap errors = new HashMap();
        request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);

        HashMap info = new HashMap();
        request.setAttribute (SessionKeys.INFO_MESSAGES, info);

        HttpSession session = request.getSession();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        String action = request.getParameter ("action");
        //added by varma 13 sep 2004
        if ((session == null) || (session.getAttribute (SessionKeys.USER_KEY) == null)) {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/notificationSetup.do");
            return (mapping.findForward("login"));
        }
        if ( user != null )
        {
            if ( user.isActionAllowed ( Functionality.NOTIFICATION_SETUP , User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }
        if ("save".equalsIgnoreCase (action)) {

            NotificationSetup notificationSetup = new NotificationSetup();

            // Extract Setup information from request

            //Commented by KumaraSwamy On Sep 1st, 2004.
            //String[] engineeringPullEmails = request.getParameterValues ("engineeringPullEmail");
            //String[] engineeringReturnEmails = request.getParameterValues ("engineeringReturnEmail");
            String[] approvedSOEmails = request.getParameterValues ("approvedSOEmails");
            String[] packingSlipEmails = request.getParameterValues ("packingSlipEmail");
            String[] adaptorLogEmails = request.getParameterValues ("adaptorLogEmail");



            // BR, march 14, 2004
            String[] shipAlertEmails = request.getParameterValues ("shipAlertEmail");
            // Added by Veeru on 17th September 2004
            String[] salesOrderEmail = request.getParameterValues ("salesOrderEmail");
            //String[] salesOrderPortingEmail = request.getParameterValues ("salesOrderPortingEmail");
            //Added by Sudhakar on 6th June 2005
           // String[] fabStageEmail = request.getParameterValues ("fabStageEmail");

           // String[] programReleaseEmail    = request.getParameterValues ( "programReleaseEmail" );
            String[] sortReleaseEmail = request.getParameterValues ("sortReleaseEmails");
            String[] assemblyReleaseEmail    = request.getParameterValues ( "assemblyReleaseEmail" );
            String[] newLotEmail    = request.getParameterValues ( "newLotEmail" );
            String[] reportsEmail    = request.getParameterValues ( "reportsEmail" );
            //notificationSetup.setEngPullEmails (engineeringPullEmails);
            //notificationSetup.setEngReturnEmails (engineeringReturnEmails);
            notificationSetup.setApprovedSOEmails (approvedSOEmails);
            notificationSetup.setPackingSlipEmails (packingSlipEmails);
            notificationSetup.setAdaptorLogEmails (adaptorLogEmails);
            notificationSetup.setSalesOrderEmails (salesOrderEmail);
            //commented by Ganesh Jan 6th, 2006
            //notificationSetup.setSalesOrderPortingEmails (salesOrderPortingEmail);
           // notificationSetup.setFabStageIdEmails(fabStageEmail);
           // notificationSetup.setProgramReleaseEmails( programReleaseEmail );
            notificationSetup.setSortReleaseEmails(sortReleaseEmail);
            notificationSetup.setAssemblyReleaseEmails( assemblyReleaseEmail );
            notificationSetup.setNewLotEmails( newLotEmail );
            notificationSetup.setReportsEmails( reportsEmail );
            // BR, march 14, 2004
            notificationSetup.setShipAlertEmails (shipAlertEmails);

            request.setAttribute ("notificationSetup", notificationSetup);

            // Validate Email Information

            //Commented by KumaraSwamy On Sep 1st, 2004.
            // 1. Validate Engineering Pull Emails
           /* if (validateEmails (engineeringPullEmails) == false) {
                errors.put ("Engineering Pull", "Invalid Email(s) are entered");
                return (mapping.findForward (retval));
            }
            notificationSetup.setEngPullEmails (engineeringPullEmails);
            request.setAttribute ("notificationSetup", notificationSetup);

            // 2. Validate Engineering Return Emails
            if (validateEmails (engineeringReturnEmails) == false) {
                errors.put ("Engineering Return", "Invalid Email(s) are entered");

                return (mapping.findForward (retval));
            }
            notificationSetup.setEngReturnEmails (engineeringReturnEmails);*/

            // 3. Validate Approved Sales Order Emails
            if (validateEmails (approvedSOEmails) == false) {
                errors.put ("Approved Sales Order", "Invalid Email(s) are entered");
                return (mapping.findForward (retval));
            }
            notificationSetup.setApprovedSOEmails (approvedSOEmails);

            // 4. Validate Packing Slip Emails
            if (validateEmails (packingSlipEmails) == false) {
                errors.put ("Packing Slip", "Invalid Email(s) are entered");
                return (mapping.findForward (retval));
            }
            notificationSetup.setPackingSlipEmails (packingSlipEmails);

            // 4. Validate Adaptor Log Emails
            if (validateEmails (adaptorLogEmails) == false) {
                errors.put ("Adaptor Log", "Invalid Email(s) are entered");
                return (mapping.findForward (retval));
            }
            notificationSetup.setAdaptorLogEmails (adaptorLogEmails);

            // BR, March 14, 2004
            // 4. Validate Ship Alert Emails
            if (validateEmails (shipAlertEmails) == false) {
                errors.put ("Ship Alert", "Invalid Email(s) are entered");
                return (mapping.findForward (retval));
            }
            notificationSetup.setShipAlertEmails (shipAlertEmails);

            if (validateEmails (salesOrderEmail) == false) {
                errors.put ("Sales Order", "Invalid Email(s) are entered");
                return (mapping.findForward (retval));
            }
          //commented by Ganesh Jan 6th, 2006
            /*if (validateEmails (salesOrderPortingEmail) == false) {
                errors.put ("Sales Order Porting", "Invalid Email(s) are entered");
                return (mapping.findForward (retval));
            }
            if (validateEmails (fabStageEmail) == false) {
                errors.put ("Fab Stage ", "Invalid Email(s) are entered");
                return (mapping.findForward (retval));
            }
            if (validateEmails (programReleaseEmail) == false)
            {
                errors.put ("Program Release ", "Invalid Email(s) are entered");
                return (mapping.findForward (retval));
            }*/

             if (validateEmails (sortReleaseEmail) == false) {
                errors.put ("Sort Release ", "Invalid Email(s) are entered");
                return (mapping.findForward (retval));
            }
            if (validateEmails (assemblyReleaseEmail) == false)
            {
                errors.put ("Assembly Release ", "Invalid Email(s) are entered");
                return (mapping.findForward (retval));
            }
            // Validate the New Lot Emails
            if ( validateEmails ( newLotEmail ) == false)
            {
                errors.put ("New Lot ", "Invalid Email(s) are entered");
                return (mapping.findForward ( retval ) );
            }
            // Validate the Reports Emails
            if ( validateEmails ( reportsEmail ) == false)
            {
                errors.put ("Report Emails ", "Invalid Email(s) are entered");
                return (mapping.findForward ( retval ) );
            }


            try {
                NotificationSetupDAO.saveNotificationSetupInfo (notificationSetup);
                info.put ("Notification Setup information has been saved", null);
                retval = "success";
            }
            catch (ScalarException se) {
                // Database failure
                System.out.println ("Couldnot save Notification Email into database -- " + se);
                errors.put ("Could not save Emails into database", null);
            }

            return (mapping.findForward (retval));
        }


        try {
            NotificationSetup notificationSetup = NotificationSetupDAO.loadNotificationSetupInfo();
            request.setAttribute ("notificationSetup", notificationSetup);
            retval = "success";
        }
        catch (ScalarException se) {
            // Exceptions while interacting with database
            errors.put ("Internal Server Error", "Could not load Notification Setup information from database");
        }

        return (mapping.findForward (retval));
    }


    private boolean validateEmails (String[] emails) {

        if (emails == null) {
            return false;
        }

        for (int i=0; i<emails.length; i++) {
            if ((emails[i] != null) && (emails[i].trim().length() != 0)) {
                if (emails[i].indexOf('@') == -1) {
                    return false;
                }
            }
        }

        return true;
    }

}